/*
 * Copyright 2010 Mttang.com All right reserved. This software is the confidential and proprietary information of
 * Mttang.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with Mttang.com.
 */
package com.mttang.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;

import com.mttang.sys.biz.action.RoleAction;

/**
 * 用于检测用户是否登陆的过滤器，如果未登录，则重定向到指的登录页面
 * <p>
 * 配置参数
 * <p>
 * checkSessionKey 需检查的在 Session 中保存的关键字 redirectURL 如果用户未登录，则重定向到指定的页面，URL不包括 ContextPath notCheckURLList
 * 不做检查的URL列表，以分号分开，并且 URL 中不包括 ContextPath
 */
public class CheckLoginFilter implements Filter {

    static org.apache.log4j.Logger log             = org.apache.log4j.Logger.getLogger(CheckLoginFilter.class);

    protected FilterConfig         filterConfig    = null;
    private String                 redirectURL     = null;
    private List                   notCheckURLList = new ArrayList();
    private String                 sessionKey      = null;

    // static ApplicationContext SpringContext;
    // static {
    // System.out.println("start filter start");
    // try{
    // SpringContext = new org.springframework.context.support.FileSystemXmlApplicationContext (new String[] {
    // "platform-web-common-context.xml",
    // "platform-web-controllers-context.xml", "platform-web-controllers-info-context.xml" });
    // }catch(Exception e){
    // log.error(e.getMessage(), e);
    // e.printStackTrace();
    //         
    // }
    // System.out.println("start filter end");
    // }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
                                                                                                                 throws IOException,
                                                                                                                 ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        ServletRequest servletRequest1 = servletRequest;
        ServletResponse servletResponse1 =  servletResponse;
        HttpSession session = request.getSession();
        // MessageSource msg = (MessageSource) this.getApplicationContext().getBean("messageSource");
        if (sessionKey == null) {
            filterChain.doFilter(request, response);
            return;
        }
        /*
         * if(b==false){ //System.out.println(session.getAttribute(sessionKey)); b=true; }
         */
        // 是否登入和是否是登入操作
        if ((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null) {
            response.sendRedirect(request.getContextPath() + redirectURL);
            return;
        }
        // 是否有此功能的权限
        if (!checkRequestURIIntNotFilterList(request)) {
            String method = request.getParameter("method");
            if (session.getAttribute(sessionKey) != null) {
                // 获取从页面传过来的参数值
                if ( "login".equals(method)) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
                Map<String, String> user = (Map) session.getAttribute(sessionKey);
                String roleId = String.valueOf(user.get("roleId"));
                String menuId = String.valueOf(session.getAttribute("prvmenuId"));
                String prv = request.getParameter("prv");
                if (request.getParameter("prvmenuId") != null && !request.getParameter("prvmenuId").equals("")) {
                    menuId = request.getParameter("prvmenuId");
                }

                // 组装输入参数 map.put(list.get(i).getValue(), "treu");
                if (menuId != null && !"".equals(menuId) && !"null".equals(menuId)) {
                    Map<String, Object> condition = new HashMap<String, Object>();
                    condition.put("roleId", roleId);
                    condition.put("menuId", menuId);
                    try {
                        // 调用app action的事件.
                        ServletContext sc = filterConfig.getServletContext();
                        WebApplicationContext context = (WebApplicationContext) sc.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
                        RoleAction roleAction = (RoleAction) context.getBean("roleAction");
                        Map<Object, Object> model = roleAction.prv(condition);
                        if (model.get("prv") != null && ((Map) model.get("prv")).get(prv).equals("true")) {
                            if(session.getAttribute("prv")!=null&&!"".equals(session.getAttribute("prv"))){
                                session.removeAttribute("prv");
                            }
                            if(session.getAttribute("prvmenuId")!=null&&!"".equals(session.getAttribute("prvmenuId"))){
                                session.removeAttribute("prvmenuId");
                            }
                            session.setAttribute("prvmenuId", menuId);
                            session.setAttribute("prv", (Map) model.get("prv"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/prvError.do?method=prvError");
                            return;
                        }
                    } catch (Exception e) {
                        response.sendRedirect(request.getContextPath() + "/prvError.do?method=prvError");
                        return;
                    }
                }else{
                    response.sendRedirect(request.getContextPath() + "/prvError.do?method=prvError");
                    return;
                }
            }
        }
        filterChain.doFilter(servletRequest1, servletResponse1);
    }

    public void destroy() {
        notCheckURLList.clear();
    }

    private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
        //String uri = request.getServletPath();
        String uri = request.getServletPath() ;
        if("/login/login.do".equals(uri)||"/advtise/advtise.do".equals(uri)
                ||"/image.do".equals(uri)||"/verify.do".equals(uri)        
        ){
            return true;
        }
        if(request.getQueryString()!=null&&!"".equals(request.getQueryString())){
            uri=uri+"?"+request.getQueryString();
        }
        boolean flg = false;
        flg = notCheckURLList.contains(uri);
        return flg;
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        redirectURL = filterConfig.getInitParameter("redirectURL");
        sessionKey = filterConfig.getInitParameter("checkSessionKey");

        String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");

        if (notCheckURLListStr != null) {
            StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");
            notCheckURLList.clear();
            while (st.hasMoreTokens()) {
                notCheckURLList.add(st.nextToken());
            }
        }
    }
}
